<script setup lang="ts" name="Result">
import API from "@/api";
import { colors, numberDigits } from "@/const/color";
import { nocache, userinfo } from "@/store";
import dayjs from "dayjs";

const { t } = useI18n();
const router = useRouter();
const images = reactive({
  expand: new URL("@/assets/images/Result/expand.png", import.meta.url).href,
  arrow: new URL("@/assets/images/Result/arrow.png", import.meta.url).href,
  reward: new URL("@/assets/images/Result/reward.png", import.meta.url).href,
});
const piniaNocache = nocache();
const piniaUserinfo: any = userinfo();
const data: any = reactive({
  currentLotteryId: 1,
  tabList: [
    { text: computed(() => t("result.test14")), value: 1 },
    { text: computed(() => t("result.test15")), value: 2 },
    {text: computed(() => t('result.test18')), value: 4 },
    {text: computed(() => t('result.test19')), value: 3 }
  ],
  showLotteryTypePicker: false,
  typeList: [],
  currentTypeId: null,
  showDatePicker: false,
  showTypePicker: false,
  pagination: {
    loading: false,
    pageNum: 1,
    pageSize: 10,
    total: 0,
  },
  cardList: [],
  currentDateInfo: ["2021", "01", "01"],
  minDate: new Date(2020, 0, 1),
  maxDate: new Date(2025, 5, 1),
  lotteryTypeList: [],
});

const {
  currentLotteryId,
  tabList,
  typeList,
  cardList,
  currentTypeId,
  showDatePicker,
  currentDateInfo,
  pagination,
  minDate,
  maxDate,
  showTypePicker,
  showLotteryTypePicker,
  lotteryTypeList,
} = toRefs(data);

const changeLang = () => {
  lotteryTypeList.value = lotteryTypeList.value.map((item: any) => {
    if (item?.children) {
      const current = item.children?.find(
        (im: any) => im.languageCode == piniaUserinfo.getLang.languageCode
      );
      if (current) {
        return {
          ...item,
          url: current?.url,
          lotteryTypeName: current.title,
        };
      }
    }
  });
};
watch(
  () => piniaUserinfo.getLang,
  (val, preVal) => {
    changeLang();
  },
  { immediate: false, deep: true }
);
const queryLotteryList = async () => {
  let res = await API.lotteryType({});
  if (res.code === 200) {
    lotteryTypeList.value = res.data;
    changeLang();
  }
};
queryLotteryList();

const comtabList = computed(() => {
  let lotteryTypeListMap = lotteryTypeList.value.map((it: any) => {
    return {
      text: it?.lotteryTypeName,
      value: it?.code,
    };
  });
  return [...tabList.value, ...lotteryTypeListMap];
});

const currentLotteryName = computed(() => {
  return comtabList.value?.find((it: any) => it.value == currentLotteryId.value)
    ?.text;
});
const currentTypeName = computed(() => {
  return typeList.value?.find((it: any) => it.value == currentTypeId.value)
    ?.text;
});
const handleLotteryItem = (item: any) => {
  currentLotteryId.value = item[0].value;
  queryPlanList();
  showLotteryTypePicker.value = false;
};
const queryPlanList = () => {
  let params = {};
  params = {
    typeConfigCode: currentLotteryId.value,
  };
  API.planListAPI(params).then((res) => {
    if (res.code === 200) {
      typeList.value = [{ text: t("result.test13"), value: 0 }, ...res.data];
      typeList.value = typeList.value.map((item: any) => {
        return {
          ...item,
          text: item.planName || item.text,
          value: item.id || item.value,
        };
      });
      currentTypeId.value = typeList.value[0].value;
      handleTypeItem([typeList.value[0]]);
    }
  });
};
queryPlanList();

const handleTypeItem = (item: any) => {
  currentTypeId.value = item[0].value;
  showTypePicker.value = false;
  cardList.value = [];
  getMyCardList();
};
const getMyCardList = () => {
  pagination.value.loading = true;
  API.lotteryPeriodListAPI({
    pageNum: pagination.value.pageNum,
    pageSize: pagination.value.pageSize,
    planId: currentTypeId.value,
    typeConfigCode: currentLotteryId.value,
  })
    .then((res) => {
      if (res?.code === 200 && res?.rows) {
        cardList.value = [...cardList.value, ...res.rows];
        pagination.value.total = res?.total || 0;
      }
    })
    .finally(() => {
      pagination.value.loading = false;
    });
};
const handleShowSelect = () => {
  showTypePicker.value = true;
};
const handleDatePicker = () => {
  showDatePicker.value = true;
};
const goDetail = (detail: any) => {
  if (detail.planName) return;
  // router.push(`/resultDetail/${detail.id}/${currentLotteryId.value+1}`);
  let data = { ...detail, periodNumList: JSON.stringify(detail.periodNumList),type:currentLotteryId.value };
  router.push({
    path: "/resultDetail",
    query: data,
  });
};
const confirmDate = (selectedValues: any, selectedOptions: any) => {
  console.log("selectedValues:", selectedValues);
  console.log("selectedOptions:", selectedOptions);
  showDatePicker.value = false;
};
const handleShowLottery = () => {
  showLotteryTypePicker.value = true;
};

const redGreenBg = (item: any) => {
  return numberDigits.find((it: any) => {
    return it.id == +item;
  })?.bg;
};

const renderSix = (listStr: string) => {
  if(!listStr) return;
  let types = ["猪", "羊", "狗", "牛", "虎", "蛇", "蛇"];
  let wins = listStr?.match(/.{1,2}/g) || [];
  return types.map((it, index) => {
    return {
      number: wins[index],
      type: it,
    };
  });
};

watch(
  () => piniaNocache.getHitBottom,
  () => {
    let totalPage = Math.ceil(
      pagination.value.total / pagination.value.pageSize
    );
    if (pagination.value.pageNum < totalPage) {
      pagination.value.pageNum++;
      getMyCardList();
    }
  }
);
watch(
  [() => currentTypeId.value, () => currentLotteryId.value],
  ([val1, val2]) => {
    cardList.value = [];
  }
);
</script>

<template>
  <div class="resultPage">
    <DetailHeader :title="t('home.btn3')" />
    <div class="resultContainer">
      <div>
        <div class="topData">
          <div class="type">
            <div class="typeData" @click="handleShowLottery">
              <div class="typeTitle">{{ t("result.title1") }}</div>
              <div class="typeItem">{{ currentLotteryName }}</div>
            </div>
          </div>
          <div class="type">
            <div class="typeData">
              <div class="typeTitle">{{ t("result.title2") }}</div>
              <div class="typeItem" @click="handleShowSelect">
                {{ currentTypeName }}
              </div>
            </div>
          </div>
          <PopSelect
            v-model:showPicker="showTypePicker"
            :columns="typeList"
            @onConfirmSelect="handleTypeItem"
            :curentId="+currentTypeId"
          />
        </div>
        <div class="rewardList">
          <div
            class="rewardItem"
            v-for="(item, index) in cardList"
            :key="index"
            @click="goDetail(item)"
          >
            <div class="left">
              <div class="topTitle">
                {{ item?.lotteryPlanName || item?.planName || "--" }}
              </div>
              <div class="time">
                <span>{{ item?.period }}</span>
                {{ dayjs(+item?.lotteryEndTime ||item.endTime).format("DD-MM-YYYY hh:mm A") }}
              </div>
              <div
                class="resultNum"
                v-if="item?.planName && item.winningNumber != null"
              >
                <span class="resultLabel">{{
                  item?.bigCode == 3 ? "排名" : t("result.test17")
                }}</span>
                <div
                  v-if="item?.bigCode == 1 || item?.bigCode == 6"
                  class="numItem"
                  v-for="el in item.winningNumber"
                >
                  {{ el }}
                </div>
                <div
                  v-if="item?.bigCode == 2"
                  class="numItem"
                  v-for="el in item.winningNumber.match(/.{1,2}/g)"
                >
                  {{ el }}
                </div>
                <div
                  v-if="item?.bigCode == 3"
                  v-for="(el, i) in item.winningNumber"
                  class="numItem3"
                >
                  <div v-if="i < 3" class="numItem3">
                    <img
                      v-if="i == 0"
                      src="@/assets/images/Race/prize1.png"
                      alt=""
                    />
                    <img
                      v-if="i == 1"
                      src="@/assets/images/Race/prize2.png"
                      alt=""
                    />
                    <img
                      v-if="i == 2"
                      src="@/assets/images/Race/prize3.png"
                      alt=""
                    />
                    <span
                      class="resItem"
                      :style="{
                        backgroundColor: colors[el - 1].bg,
                        borderColor: colors[el - 1].border,
                      }"
                      >{{ el }}</span
                    >
                  </div>
                </div>
                <div
                  v-if="item?.bigCode == 4"
                  v-for="(el, i) in item.winningNumber"
                  class="numItem4"
                >
                  <span
                    class="radius"
                    :style="{
                      background: redGreenBg(el),
                    }"
                    >{{ el }}</span
                  >
                </div>
                <div
                  v-if="item.bigCode == 5"
                  class="numItem5"
                >
                <div class="sixItem"
                  v-for="(itCont, index) in renderSix(item.winningNumber)"
                  :key="index">
                  <p>{{ itCont.number }}</p>
                  <p>{{ itCont.type }}</p>
                </div>
                </div>
              </div>
            </div>
            <img class="rewardImg" :src="images.reward" alt="" />
            <Iconfont
              name="icon-icon_jiantou2"
              color="#FC3666"
              size="20"
              v-if="!item?.planName"
              class="arrowRight"
            />
          </div>
        </div>
        <van-popup
          v-model:show="showDatePicker"
          round
          position="bottom"
          :style="{ height: '50%' }"
        >
          <van-date-picker
            v-model="currentDateInfo"
            :min-date="minDate"
            :max-date="maxDate"
            @cancel="showDatePicker = false"
            @confirm="confirmDate"
          />
        </van-popup>
      </div>
      <!-- 彩种下拉 -->
      <PopSelect
        v-model:showPicker="showLotteryTypePicker"
        :columns="comtabList"
        @onConfirmSelect="handleLotteryItem"
        :curentId="+currentLotteryId"
        :title="t('result.test11')"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import url("./index.scss");
</style>
